const financeFamily = require('../../../../utils/finance-home');
const app = getApp();
function formatTime(ts) {
  if (!ts) return '';
  const d = new Date(ts);
  const pad = n => n < 10 ? '0' + n : n;
  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
Page({
  data: {
    hasFamily: false,
    familyInfo: {},
    inviteCode: '',
    showCreateInput: false,
    showJoinInput: false,
    createName: '',
    joinCode: '',
    confirmModal: { show: false, title: '', msg: '', action: '' },
  },
  async onLoad() {
    await this.fetchFamily();
  },
  async fetchFamily() {
    const res = await financeFamily.getMyFamily();
    console.log('getMyFamily返回', res);
    if (res && (res.familyName || res.familyId)) {
      res.id = res.id || res.familyId;
      res.type = res.type || res.role || 'creator';
      res.list = res.list || res.members || [];
      res.familyTimeFmt = formatTime(res.time);
      this.setData({ hasFamily: true, familyInfo: res, inviteCode: '' });
    } else {
      this.setData({ hasFamily: false, familyInfo: {}, inviteCode: '' });
    }
  },
  // 创建/加入家庭弹窗
  showCreate() { this.setData({ showCreateInput: true, showJoinInput: false, createName: '' }); },
  showJoin() { this.setData({ showJoinInput: true, showCreateInput: false, joinCode: '' }); },
  hideInputModal() { this.setData({ showCreateInput: false, showJoinInput: false }); },
  onCreateNameInput(e) { this.setData({ createName: e.detail.value }); },
  onJoinCodeInput(e) { this.setData({ joinCode: e.detail.value }); },
  // 创建家庭
  async onCreateFamily() {
    const name = this.data.createName.trim();
    if (!name) return wx.showToast({ title: '请输入家庭名称', icon: 'none' });
    if (name.length > 10) return wx.showToast({ title: '最多10个字', icon: 'none' });
    // 假设有createFamily接口
    if (!financeFamily.createFamily) return wx.showToast({ title: '未实现', icon: 'none' });
    wx.showLoading({ title: '创建中...' });
    try {
      await financeFamily.createFamily(name);
      wx.hideLoading();
      this.setData({ showCreateInput: false });
      // 清空本地的账户缓存
      wx.removeStorageSync('accountBooks');
      await this.fetchFamily();
    } catch (e) {
      wx.hideLoading();
      wx.showToast({ title:  (e && e.data && e.data.msg) || '创建家庭失败', icon: 'none' });
    }
  },
  // 加入家庭
  async onJoinFamily() {
    const code = this.data.joinCode.trim();
    if (!code) return wx.showToast({ title: '请输入邀请码', icon: 'none' });
    // 假设有joinFamily接口
    if (!financeFamily.joinFamily) return wx.showToast({ title: '未实现', icon: 'none' });
    wx.showLoading({ title: '加入中...' });
    try {
      await financeFamily.joinFamily(code);
      wx.hideLoading();
      this.setData({ showJoinInput: false });
      // 清空本地的账户缓存
      wx.removeStorageSync('accountBooks');
      await this.fetchFamily();
    } catch (e) {
      console.log('joinFamily失败', e);
      wx.hideLoading();
      wx.showToast({ title:  (e && e.data && e.data.msg) || '加入失败', icon: 'none' });
    }
  },
  // 生成邀请码
  async onGenerateInvite() {
    const familyId = this.data.familyInfo.id;
    if (!familyId) return;
    wx.showLoading({ title: '生成中...' });
    try {
      const res = await financeFamily.generateInviteCode(familyId);
      wx.hideLoading();
      await this.fetchFamily();
    } catch (e) {
      wx.hideLoading();
      wx.showToast({ title:  (e && e.data && e.data.msg) || '生成邀请码失败', icon: 'none' });
    }
  },
  // 解散/退出家庭
  onDissolve() {
    this.setData({ confirmModal: { show: true, title: '解散家庭', msg: '确定要解散该家庭吗？', action: 'dissolve' } });
  },
  onQuit() {
    this.setData({ confirmModal: { show: true, title: '退出家庭', msg: '确定要退出该家庭吗？', action: 'quit' } });
  },
  onConfirmModalOk() {
    const { action } = this.data.confirmModal;
    if (action === 'dissolve') this.doDissolve();
    if (action === 'quit') this.doQuit();
  },
  onConfirmModalCancel() {
    this.setData({ confirmModal: { show: false, title: '', msg: '', action: '' } });
  },
  async doDissolve() {
    const familyId = this.data.familyInfo.id;
    if (!familyId) return;
    wx.showLoading({ title: '解散中...' });
    try {
      await financeFamily.dissolveFamily(familyId);
      wx.hideLoading();
      this.setData({ confirmModal: { show: false } });
      wx.showToast({ title: '已解散', icon: 'none' });
      // 清空本地的账户缓存
      wx.removeStorageSync('accountBooks');
      setTimeout(() => wx.navigateBack(), 600);
    } catch (e) {
      wx.hideLoading();
      wx.showToast({ title:  (e && e.data && e.data.msg) || '解散家庭失败', icon: 'none' });
    }
  },
  async doQuit() {
    const familyId = this.data.familyInfo.id;
    if (!familyId) return;
    wx.showLoading({ title: '退出中...' });
    try {
      await financeFamily.quitFamily(familyId);
      wx.hideLoading();
      this.setData({ confirmModal: { show: false } });
      wx.showToast({ title: '已退出', icon: 'none' });
      // 清空本地的账户缓存
      wx.removeStorageSync('accountBooks');
      setTimeout(() => wx.navigateBack(), 600);
    } catch (e) {
      wx.hideLoading();
      wx.showToast({ title:  (e && e.data && e.data.msg) || '退出家庭失败', icon: 'none' });
    }
  },
  // 复制邀请码
  onCopyInviteCode() {
    const code = this.data.familyInfo.inviteCode || this.data.inviteCode;
    if (!code) return;
    wx.setClipboardData({
      data: code,
      success: () => {
        wx.showToast({ title: '邀请码已复制', icon: 'none' });
      }
    });
  },
}); 